﻿using System;
using System.Text;
using System.Web;
using System.Web.Security;
using MvcCms.Service.Logging;

namespace MvcCms.Service.Code.Encryption
{
    public static class MvcCmsEncryption
    {
        public static string Decrypt(string value)
        {
            if (string.IsNullOrEmpty(value)) { return null; }
            try
            {
                var decryptedBytes = MachineKey.Decode(value, MachineKeyProtection.All);
                return Encoding.UTF8.GetString(decryptedBytes);
            }
            catch (Exception ex)
            {
                AppLogging.GetLogger().Error(GeneralMethods.GetStackNames(), ex);
                throw new HttpException("Unable to Decrypt.", ex);
            }
        }

        public static string Encrypt(string value)
        {
            try
            {
                var plaintextBytes = Encoding.UTF8.GetBytes(value);
                return MachineKey.Encode(plaintextBytes, MachineKeyProtection.All);
            }
            catch (Exception ex)
            {
                AppLogging.GetLogger().Error(GeneralMethods.GetStackNames(), ex);
                throw new HttpException("Unable to encrypt.", ex);
            }
        }



    }
}
